package com.ruoyi.tb.lmt.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.impl.SysDeptServiceImpl;
import com.ruoyi.tb.lmt.domain.bo.TbRepairplanBo;
import com.ruoyi.tb.lmt.domain.bo.TbWorktemplateBo;
import com.ruoyi.tb.lmt.domain.vo.TbRepairplanVo;
import com.ruoyi.tb.lmt.domain.vo.TbWorktemplateVo;
import lombok.RequiredArgsConstructor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.tb.lmt.domain.vo.TbLocomotiveVo;
import com.ruoyi.tb.lmt.domain.bo.TbLocomotiveBo;
import com.ruoyi.tb.lmt.service.ITbLocomotiveService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 大机配属
 *
 * @author ruoyi
 * @date 2023-11-30
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xha-lmt/locomotive")
public class TbLocomotiveController extends BaseController {

    private final ITbLocomotiveService iTbLocomotiveService;
    private final ISysDeptService iSysDeptService;

    /**
     * 查询大机配属列表
     */
    //@SaCheckPermission("xha-lmt:locomotive:list")
    @GetMapping("/list")
    public TableDataInfo<TbLocomotiveVo> list(TbLocomotiveBo bo, PageQuery pageQuery) {
        return iTbLocomotiveService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出大机配属列表
     */
    @SaCheckPermission("xha-lmt:locomotive:export")
    @Log(title = "大机配属", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TbLocomotiveBo bo, HttpServletResponse response) {
        List<TbLocomotiveVo> list = iTbLocomotiveService.queryList(bo);
        ExcelUtil.exportExcel(list, "大机配属", TbLocomotiveVo.class, response);
    }

    /**
     * 获取大机配属详细信息
     *
     * @param ID 主键
     */
    @SaCheckPermission("xha-lmt:locomotive:query")
    @GetMapping("/{ID}")
    public R<TbLocomotiveVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long ID) {
        return R.ok(iTbLocomotiveService.queryById(ID));
    }

    @SaCheckPermission("xha-lmt:locomotive:importExcel")
    @PostMapping(value = "/importExcel", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<List<TbLocomotiveVo>> importExcel(@RequestPart("file") MultipartFile file) throws Exception {
        // 处理解析结果
        ExcelResult<TbLocomotiveVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), TbLocomotiveVo.class,true);
        // 获取从 excelResult.getList() 中获取的 TbLocomotiveVo 列表
        // 找出 id 为 null 的子集合
        List<TbLocomotiveVo> voList = excelResult.getList();
        /*List<TbLocomotiveVo> idIsNullList = voList.stream()
            .filter(vo -> vo.getID() == null)
            .collect(Collectors.toList());

        // 找出 id 不为 null 但在 tb_worktemplate 表中不存在的子集合
        List<TbLocomotiveVo> idNotExistInDBList = voList.stream()
            .filter(vo -> vo.getID() != null)
            .filter(vo -> !iTbLocomotiveService.existsById(vo.getID()))
            .collect(Collectors.toList());

        // 结合两个子集合，形成新的集合
        List<TbLocomotiveVo> newVoList = new ArrayList<>();
        newVoList.addAll(idIsNullList);*/
        /*newVoList.addAll(idNotExistInDBList);*/
        /*// 更新操作：找出 id 存在于数据库中的子集合并执行更新操作
        List<TbLocomotiveVo> idExistInDBList = voList.stream()
            .filter(vo -> vo.getID() != null)
            .filter(vo -> iTbLocomotiveService.existsById(vo.getID()))
            .collect(Collectors.toList());


        // 更新数据库中已存在的数据
        for (TbLocomotiveVo vo : idExistInDBList) {

        }*/


        // 创建一个空的 TbWorktemplateBo 列表，用于存放转换后的对象
        List<TbLocomotiveBo> boList = new ArrayList<>();

        // 遍历 TbWorktemplateVo 列表，进行转换
        for (int i = 0; i < voList.size(); i++) {
            TbLocomotiveVo vo = voList.get(i);
            TbLocomotiveBo bo = new TbLocomotiveBo();
            bo.setLmtType(vo.getLmtType());
            bo.setLmtNumber(vo.getLmtNumber());
            bo.setLmtCode(vo.getLmtCode());
            bo.setMadeDate(vo.getMadeDate());
            bo.setUserDate(vo.getUserDate());
            bo.setMadeFactory(vo.getMadeFactory());
            bo.setLmtLength(vo.getLmtLength());
            bo.setLmtWeight(vo.getLmtWeight());
            bo.setWorkteamname(vo.getWorkteamname());
            SysDept sysDept = iSysDeptService.selectByName(vo.getWorkteamname());
            if (sysDept==null){
                return R.fail("没有找到第"+i+1+"的配属车间名称有误！");
            }
            bo.setWorkteamId(sysDept.getDeptId());
            bo.setWorkGroup(vo.getWorkGroup());
            SysDept sysDept1 = iSysDeptService.selectByName(vo.getWorkGroup());
            if (sysDept1==null){
                return R.fail("没有找到第"+i+1+"的配属车间名称有误！");
            }
            bo.setWorkGroupId(sysDept1.getDeptId());
            bo.setLastRepairChar(vo.getLastRepairChar());
            bo.setLastRepairDate(vo.getLastRepairDate());
            bo.setStatus(vo.getStatus());
            bo.setRemark(vo.getRemark());
            bo.setLongFactor(vo.getLongFactor());
            boList.add(bo);
        }

        for (TbLocomotiveBo bo : boList) {
            iTbLocomotiveService.insertByBo(bo);
        }

        return R.ok();
    }

    //导入模板
    @SaCheckPermission("xha-lmt:locomotive:exportPlan")
    @RequestMapping(value = "/excel/export")
    public void export(HttpServletRequest request, HttpServletResponse response){
        iTbLocomotiveService.export(request,response);
    }
    /**
     * 新增大机配属
     */
    @SaCheckPermission("xha-lmt:locomotive:add")
    @Log(title = "大机配属", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TbLocomotiveBo bo) {
        return toAjax(iTbLocomotiveService.insertByBo(bo));
    }

    /**
     * 修改大机配属
     */
    @SaCheckPermission("xha-lmt:locomotive:edit")
    @Log(title = "大机配属", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TbLocomotiveBo bo) {
        return toAjax(iTbLocomotiveService.updateByBo(bo));
    }

    /**
     * 删除大机配属
     *
     * @param IDs 主键串
     */
    @SaCheckPermission("xha-lmt:locomotive:remove")
    @Log(title = "大机配属", businessType = BusinessType.DELETE)
    @DeleteMapping("/{IDs}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] IDs) {
        return toAjax(iTbLocomotiveService.deleteWithValidByIds(Arrays.asList(IDs), true));
    }

    //选择无计划大机
    @SaCheckPermission("xha-lmt:locomotive:lmtListByStatus")
    @GetMapping("/lmtListByStatus")
    public TableDataInfo<TbLocomotiveVo> lmtListByStatus(TbLocomotiveBo bo,PageQuery pageQuery) {
        return iTbLocomotiveService.lmtListByStatus(bo,pageQuery);
    }

    @SaCheckPermission("xha-lmt:locomotive:selectByLmtType")
    @GetMapping("/query/selectByLmtType")
    public R<?> selectByLmtType(String lmtType) {
        return R.ok(iTbLocomotiveService.selectByLmtType(lmtType));
    }

    //根据车号查车型
    @GetMapping("/query/selectByLmtNumber")
    public R<?> selectByLmtNumber(String lmtNumber) {
        return R.ok(iTbLocomotiveService.selectByLmtNumber(lmtNumber));
    }

    //查询所有车号
    @GetMapping("/query/selectBy")
    public R<?> selectBy() {
        return R.ok(iTbLocomotiveService.selectBy());
    }
}
